/**
 * 验证码工具函数
 * 用于生成模拟验证码，便于前端开发和测试
 */

/**
 * 生成随机验证码
 */
export const generateRandomCaptcha = (length: number = 4): string => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};

/**
 * 生成验证码图片的SVG
 */
export const generateCaptchaSVG = (text: string): string => {
  const width = 120;
  const height = 40;
  
  // 生成随机背景色
  const bgColors = ['#f0f0f0', '#e6f7ff', '#f6ffed', '#fff7e6', '#f9f0ff'];
  const bgColor = bgColors[Math.floor(Math.random() * bgColors.length)];
  
  // 生成随机干扰线
  const lines = [];
  for (let i = 0; i < 3; i++) {
    const x1 = Math.random() * width;
    const y1 = Math.random() * height;
    const x2 = Math.random() * width;
    const y2 = Math.random() * height;
    const color = `hsl(${Math.random() * 360}, 50%, 70%)`;
    lines.push(`<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" opacity="0.5"/>`);
  }
  
  // 生成随机干扰点
  const dots = [];
  for (let i = 0; i < 20; i++) {
    const x = Math.random() * width;
    const y = Math.random() * height;
    const color = `hsl(${Math.random() * 360}, 50%, 60%)`;
    dots.push(`<circle cx="${x}" cy="${y}" r="1" fill="${color}" opacity="0.6"/>`);
  }
  
  // 生成文字
  const chars = text.split('');
  const charWidth = width / chars.length;
  const textElements = chars.map((char, index) => {
    const x = index * charWidth + charWidth / 2;
    const y = height / 2 + (Math.random() - 0.5) * 10;
    const rotation = (Math.random() - 0.5) * 30;
    const fontSize = 16 + Math.random() * 8;
    const color = `hsl(${Math.random() * 60 + 200}, 70%, 40%)`;
    
    return `<text x="${x}" y="${y}" font-family="Arial, sans-serif" font-size="${fontSize}" 
            fill="${color}" text-anchor="middle" transform="rotate(${rotation} ${x} ${y})" 
            font-weight="bold">${char}</text>`;
  });
  
  const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <rect width="100%" height="100%" fill="${bgColor}"/>
      ${lines.join('')}
      ${dots.join('')}
      ${textElements.join('')}
    </svg>
  `;
  
  return `data:image/svg+xml;base64,${btoa(svg)}`;
};

/**
 * 生成完整的验证码数据
 */
export const generateCaptchaData = () => {
  const captchaText = generateRandomCaptcha(4);
  const captchaImage = generateCaptchaSVG(captchaText);
  const captchaId = `captcha_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  
  return {
    captchaId,
    captchaImage,
    captchaText, // 用于测试，实际项目中不应该返回
    expiresIn: 300 // 5分钟过期
  };
};

/**
 * 验证验证码
 */
export const verifyCaptchaCode = (_captchaId: string, inputCode: string, correctCode: string): boolean => {
  // 简单的验证逻辑，实际项目中应该通过后端验证
  return inputCode.toUpperCase() === correctCode.toUpperCase();
};
